/*! ******************************************************************************
 *
 * Pentaho Data Integration
 *
 * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.pentaho.di.core.plugins;

import java.net.URL;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.util.StrUtil;

public class KettleSelectiveParentFirstClassLoader extends KettleURLClassLoader {

	/**
	 * 匹配模型, 匹配成功则优先使用父加载器加载类
	 */
	private final List<Pattern> patterns;

	public KettleSelectiveParentFirstClassLoader(URL[] url, ClassLoader parent, String[] patterns) {
		super(url, parent);
		this.patterns = initPatterns(patterns);
	}

	public KettleSelectiveParentFirstClassLoader(URL[] url, ClassLoader parent, String classLoaderName, String[] patterns) {
		super(url, parent, classLoaderName);
		this.patterns = initPatterns(patterns);
	}

	private List<Pattern> initPatterns(String[] patterns) {
		return Stream.of(patterns).filter(StrUtil::isNotBlank).map(Pattern::compile).collect(Collectors.toList());
	}

	private Class<?> loadClassParentFirst(String className, boolean resolveClass) throws ClassNotFoundException {
		try {
			return loadClassFromParent(className, resolveClass);
		} catch (ClassNotFoundException e) {
			// ignore
		} catch (NoClassDefFoundError e) {
			// ignore
		}

		return loadClassFromThisLoader(className, resolveClass);
	}

	@Override
	protected synchronized Class<?> loadClass(String className, boolean resolveClass) throws ClassNotFoundException {
		for (Pattern pattern : patterns) {
			if (pattern.matcher(className).matches()) {
				return loadClassParentFirst(className, resolveClass);
			}
		}
		return super.loadClass(className, resolveClass);
	}
}
